<?php
/**
 * Created by PhpStorm.
 * User: Daxu
 * Date: 2018/3/4
 * Time: 11:11
 */

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\AdminLog;
use App\Models\Professional;
use App\Models\Student;
use App\Models\UserCan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class ProfessionalController extends Controller
{
    private $errorNum = 0;
    private $successNum = 0;

    public function getList()
    {
        return Professional::query()->pluck('name', 'id');
    }

    public function check(Request $request)
    {
        $open_id = $request->get('open_id', '');
        \DB::beginTransaction();
        try {
            $student = Student::query()->where(['wx_key' => $open_id])->first();
            if ($student) {
                $can = UserCan::query()->where('user_id', $student->id)->first();
                if ($can) {
                    if ($can->number == 0) {
                        throw new \Exception('已达到上传上限');
                    }
                } else {
                    throw new \Exception('未获得上传许可');
                }
            } else {
                throw new \Exception('未找到该学生');
            }

            \DB::commit();
            return ['success' => 'true', 'message' => '获得许可'];
        } catch (\Exception $e) {
            \DB::rollback();
            return ['success' => 'false', 'message' => $e->getMessage()];
        }
    }

    public function upload(Request $request)
    {
        $file = $request->file('file');
        $open_id = $request->get('openId');
        $name = $request->get('name');
        $grade = $request->get('grade');
        $isCollage = $request->get('isCollage');
        $filename = '';
        \DB::beginTransaction();
        try {
            $student = Student::query()->where(['wx_key' => $open_id])->first();
            if ($student) {
                $can = UserCan::query()->where('user_id', $student->id)->first();
                if ($can->number == 0) {
                    throw new \Exception('可上传数量已达到上限');
                }
                $pro = Professional::query()->where(['name' => $name, 'user_id' => $student->id])->first();
                if ($pro) {
                    throw new \Exception('该证书已经提交过了');
                }
                if ($name!='无'){
                    if(!$file){
                        throw new \Exception('请上传附件');
                    }
                    $extension = $file->getClientOriginalExtension();
                    $savePath = public_path('') . '/files_store';
                    $filename = $student->u_name . $student->u_code . $name . '.' . $extension;
                    $file->move($savePath, $filename);
                }
                $pro = new Professional();
                $pro->name = $name;
                $pro->user_id = $student->id;
                if ($name!='无'){
                    $pro->grade = $grade;
                    $pro->is_college = $isCollage;
                    $pro->path = 'files_store/' . $filename;
                }
                if (!$pro->save()) {
                    throw new \Exception('保存证书失败');
                }
                $can->number -= 1;
                if (!$can->save()) {
                    throw new \Exception('可上传数量变更失败');
                }
            } else {
                throw new \Exception('未找到该学生');
            }
            \DB::commit();
            return ['success' => 'true', 'message' => '上传成功'];
        } catch (\Exception $e) {
            \DB::rollback();
            return ['success' => 'false', 'message' => $e->getMessage()];
        }

    }

    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = Professional::with(['user'])
            ->where('name', 'like', '%' . $queryString . '%')
            ->orWhereHas('user', function ($query) use ($queryString) {
                return $query->where('u_name', 'like', '%' . $queryString . '%');
            })
            ->paginate();
        return $models;
    }

    public function import(Request $request)
    {
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "1024M");
        $this->user = $request->get('user');
        if ($request->ajax()) {
            $file = $request->file('file');
            // 第一个参数代表目录, 第二个参数代表我上方自己定义的一个存储媒介
            $extension = $file->getClientOriginalExtension();
            $savePath = public_path('') . '/files_store';
            $filename = 'daorupro.' . $extension;
            $file->move($savePath, $filename);
//            $path = $file->store('avatars', 'uploads');
            Excel::load($savePath . '/' . $filename, function ($reader) {
                $reader1 = $reader->getSheet(0);
                $results = $reader1->toArray();
                //  dd($results);
                foreach ($results as $key => $items) {
                    if ($key == 0) {
                        continue;
                    }

                    \DB::beginTransaction();
                    try {
                        $student_code = $items[2];
                        $student = Student::query()->where('u_code', $student_code)->first();
                        if ($student) {
                            $can = UserCan::query()->where('user_id', $student->id)->first();
                            if (!$can) {
                                $can = new UserCan();
                                $can->user_id = $student->id;
                                $can->number = 5;
                                if (!$can->save()) {
                                    throw new \Exception('保存失败');
                                }
                            }
                        } else {
                            throw new \Exception('未找到该学生');
                        }
                        \DB::commit();
                        $this->successNum += 1;
                    } catch (\Exception $e) {
                        \DB::rollback();
                        $this->errorNum += 1;
                    }
                }
                $logs = new AdminLog();
                $logs->admin = 1;
                $logs->logs = '导入上传资质人员信息，成功' . $this->successNum . '条，失败' . $this->errorNum . '条';
                $logs->save();
                if ($this->errorNum) {
                    return response($this->errorNum, 406);
                } else {
                    return response('导入成功', 200);
                }
            });

        }
    }
    public function export(){
        $cellData = [
            ['姓名', '学号', '证书名称', '证书等级', '是否大专考取']
        ];
        $query = Professional::query()->get();
        if($query){
            foreach ($query as $item) {
                $student = Student::query()->where('id',$item->user_id)->first();
                $res[] = $student->u_name;
                $res[] = $student->u_code;
                $res[] = $item->name;
                $res[] = $item->grade;
                $res[] = $item->is_college;
                $cellData[] = $res;
                unset($res);
            }
        }
        Excel::create('证书统计', function ($excel) use ($cellData) {
            $excel->sheet('result', function ($sheet) use ($cellData) {
                $sheet->rows($cellData);
            });
        })->export('xls');
    }
    public function professionalUser(Request $request)
    {
        $queryString = $request->get('query', '');
        $models = UserCan::with(['user'])
            ->whereHas('user', function ($query) use ($queryString) {
                return $query->where('u_name', 'like', '%' . $queryString . '%');
            })
            ->paginate();
        return $models;
    }

    /**
     * 添加科室
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Professional();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Professional $Professional, Request $request)
    {
        $Professional->fill($request->all());
        if ($Professional->save()) {
            return $Professional;
        } else {
            return response($Professional->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show(Professional $Professional)
    {
        return $Professional;
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = Professional::findOrFail($id);
        return $model;
    }
}
